package com.tonann.app.mq;

import com.alibaba.fastjson2.JSONObject;
import com.rabbitmq.client.Channel;
import com.tonann.app.domain.AppSensor;
import com.tonann.app.mqtt.dao.DataBody;
import com.tonann.app.mqtt.dao.MQTTSensor;
import com.tonann.app.task.AnalyseTask;
import com.tonann.common.utils.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;

//@Component
public class WorkConsumers {

    @Resource
    private AnalyseTask analyseTask;

    @RabbitListener(queues = "work_queue")//队列的名称
    public void readMessage(Message message, Channel channel) {
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            new Thread(
                    new Runnable() {
                        @Override
                        public void run() {
                            System.out.println("我是消费信息111：" + new String(message.getBody()));
                            String body = new String(message.getBody());
                            DataBody dataBody = JSONObject.parseObject(body, DataBody.class);
                            long start = System.nanoTime();
                            String deviceId = dataBody.getId();
                            String v = dataBody.getValue();
                            if (StringUtils.isNotEmpty(v)) {
                                if (v.trim().equals("true")) {
                                    v = "1";
                                } else if (v.trim().equals("false")) {
                                    v = "0";
                                }
                                AppSensor sensor = MQTTSensor.getInstance().map.get(deviceId);
                                if (sensor != null) {
                                    float result = new BigDecimal(v).setScale(2, RoundingMode.DOWN).floatValue();
                                    Long magnification = sensor.getMagnification() == null ? 1L : sensor.getMagnification();
                                    float r = result / magnification;
                                    BigDecimal bigDecimal = new BigDecimal(r + "");
                                    bigDecimal = bigDecimal.setScale(2, RoundingMode.DOWN);
                                    sensor.setValue(bigDecimal.floatValue()+"");
                                    analyseTask.faultAnalyse(sensor );
                                }
                            }
                            long end = System.nanoTime();
                            System.out.println("一个数据处理时间：" + (end - start));

                        }
                    }

            ).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
